import { ref } from 'vue'
import is from '@/utils/is'
import { adapter, request } from '@/request'
import { keywordListByGet } from '@/core/api/priceSheet'
import { message } from 'ant-design-vue'
import type { PriceKeyword } from '@/core/interfaces/keyword'
import { PlatformEnum, ProductEnum } from '@/core/enums/platform'
import type { RequestWrapper } from '@/core/interfaces/common'
import { LandingPageEnum, IsFromHjzwEnum } from '@/core/enums/type'
import { ComboPriceNameEnum } from '@/core/enums/name'

export interface HjbwPriceAskParams {
  cibao?: ProductEnum.HJBW
  keyword?: string
  packageId?: number
  onLinePeriod?: string
  shopType?: LandingPageEnum
  areas?: string[]
  comboPriceName?: ComboPriceNameEnum
  comboPrice?: number
  hzTransferCode?: IsFromHjzwEnum
  hzNotes?: string
}

export default function getKeywordList() {
  const service = adapter<
    RequestWrapper<{
      wordPV: PriceKeyword[]
      heatWords: PriceKeyword[]
    }>
  >(request)
  const loading = ref(false)
  const response = ref<PriceKeyword[]>([])

  const fetch = (data: HjbwPriceAskParams) => {
    const { url, method } = keywordListByGet()
    loading.value = true

    const item = data.keyword
      .toLowerCase()
      .split(/[\n\r\s,，;；]+/g)
      .filter((t) => t !== '')
    return service({
      config: {
        url,
        method,
        data: {
          keywords: item,
          productId: data.productId
        }
      },
      callback: (res) => {
        function formatter(item: PriceKeyword) {
          let disabled = false
          if (item.clientType === PlatformEnum.PC && item.heatRate > 20) {
            disabled = true
          }
          if (item.clientType === PlatformEnum.MOBILE && item.heatRate >= 6) {
            disabled = true
          }

          return {
            ...item,
            frontKey: `${item.name}|-|${item.clientType}`,
            selected: false,
            reasons: item.showReasons ? item.showReasons.split(',') : [],
            loading: false,
            disabled
          }
        }

        const wordPV = res.data.data.wordPV.map(formatter).filter((item) => item.clientType === PlatformEnum.PC)
        const heatWords = res.data.data.heatWords.map(formatter).filter((item) => item.clientType === PlatformEnum.PC)

        response.value = wordPV.concat(heatWords)
      },
      error: (err) => {
        if (is.error(err)) {
          message.error(err.message)
        }
      },
      done: () => {
        loading.value = false
      }
    })
  }

  return [response, fetch, loading] as const
}
